package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ActivityCompletedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.CustomEventHandler;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ProcessCompletedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.common.api.delegate.event.FlowableEvent;
import org.flowable.engine.common.api.delegate.event.FlowableEventType;
import org.flowable.engine.delegate.event.impl.FlowableActivityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ActivityCompletedHandler implements CustomEventHandler {
    @Lazy
    @Autowired(required = false)
    private List<ActivityCompletedPostProcessor> activityCompletedPostProcessors = new ArrayList<>();

    @Override
    public FlowableEventType getEventType() {
        return FlowableEngineEventType.ACTIVITY_COMPLETED;
    }

    @Override
    public void handle(FlowableEvent event) throws EventCallSuspendException {
        FlowableActivityEventImpl activityEvent = (FlowableActivityEventImpl) event;
        executePostProcessors(activityEvent);
    }

    private void executePostProcessors(FlowableActivityEventImpl activityEvent) throws EventCallSuspendException {
        for (ActivityCompletedPostProcessor processor : activityCompletedPostProcessors) {
            try {
                processor.process(activityEvent);
            } catch (EventCallSuspendException e) {
                log.warn(e.getMessage());
                throw e;
            } catch (Exception e) {
                log.warn("节点结束时，执行自定义逻辑发生异常：{}", ExceptionUtil.stacktraceToString(e));
            }
        }
    }

}
